package com.veo.controller;

import com.github.pagehelper.PageInfo;
import com.veo.domain.Orders;
import com.veo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;


@Controller
@RequestMapping("/orderController")
public class OrderController {

    @Autowired
    private OrderService orderService;


    @RequestMapping("/findAllOrders")
    public ModelAndView findAllOrders(@RequestParam(value = "page",defaultValue = "1",required = false)Integer page,@RequestParam(value = "size",defaultValue = "5",required = false)Integer size,@RequestParam(value = "searcherName",defaultValue = "",required = false)String searcherName) throws UnsupportedEncodingException {
        ModelAndView mv=new ModelAndView();
        if (!(Charset.forName("GBK").newEncoder().canEncode(searcherName))) {
            //转码UTF8
            searcherName = new String(searcherName.getBytes("ISO-8859-1"), "utf-8");
        }
        List<Orders> orders = orderService.findAllOrders(page,size,searcherName);
        PageInfo allOrders=new PageInfo(orders);
        mv.addObject("ordersList",allOrders);
        mv.addObject("searcherName",searcherName);
        mv.setViewName("orders-list");
        return mv;
    }

    @RequestMapping("/findOrdersById")
    public ModelAndView findOrdersById(String id){
        ModelAndView mv=new ModelAndView();
        Orders orders = orderService.findOrdersById(id);
        mv.addObject("orders",orders);
        mv.setViewName("orders-show");
        return mv;
    }

    @RequestMapping("deleteOrderByIds")
    public String deleteOrderByIds(String idStr){
        if (idStr!=null && idStr.length()>0&& idStr!=""){
            String[] ids = idStr.split(",");
            for (String id : ids) {
                orderService.deleteOrderTravellerId(id);
                orderService.deleteOrderById(id);
            }
        }
        return "redirect:findAllOrders";
    }
}
